
import React, { useState, useCallback, useEffect } from 'react';
import { fjAndDgDataCode, intl, resDataFilter } from '@/utils';
import Form, { SimpleItem, GroupItem, } from 'devextreme-react/form';
import 'devextreme-react/text-area';
import { request, useModel } from 'umi';
import notify from 'devextreme/ui/notify';
import { getPaperProps } from '../../../../service';
import Button from 'devextreme-react/button';
import useWindowResize from '../../../../../../components/useWindowResize';
import { getCpasIcon } from '@/utils/icon';
import TextBox from 'devextreme-react/text-box';

const DgProps = ({ dgChangeTime, dgid, onCloseDrawer, RefreshFj }: any) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, zcbfid, sjxmbh } = initialState?.curPart as API.CurPart;
  const [dataFormObj, setDataFormObj] = useState<any>({});

  const [dataFormLXItem, setDataFormLXItem] = useState<any>([]);
  const [dataFormDgsyyItem, setDataFormDgsyyItem] = useState<any>([]);


  const { height, width } = useWindowResize();
  // 获取 审计阶段列表
  const fetchData = async (dgidStr: string) => {
    const res = await getPaperProps(dbname, zcbfid, dgidStr, sjxmbh);
    if (res.success) {
      setDataFormLXItem(res.data.lx?.data ?? []);
      setDataFormDgsyyItem(res.data.dgsyy?.data ?? []);
      setDataFormObj(() => {
        const tempDGSYY = res.data?.dgsyy?.selected ?? null;
        const tempLX = res.data?.lx?.selected ?? null;
        let newData = { ...res.data, dgsyy: tempDGSYY, lx: tempLX };
        return newData;
      });

    } else {
      notify({
        message: '获取数据失败！',
        type: 'error',
      });
    }
  };

  useEffect(() => {
    fetchData(dgid);
  }, [dgid, dgChangeTime]);


  async function changeProperty(dataForm: any, sjxmbh: any, dataDgid: string, dbname: string) {
    // construct a request body
    if (Object.keys(dataForm).length === 0) {
      notify({
        message: intl('paper.noChange', '没有变化'),
        type: 'warning',
      });
      return;
    };
    const body: {
      dgid: string;
      dgmc: string;
      dglx: string;
      dgsyh: string;
      PaperIndexNo: string;
      sjxmbh: string;
      dgsyy?: string;
      lx?: string;
      dbname: string
    } = {
      dgid: dataDgid,
      dgmc: dataForm?.DGMC,
      dglx: dataForm?.DGLX,
      dgsyh: dataForm?.DGSYH,
      PaperIndexNo: dataForm?.PaperIndexNo,
      sjxmbh: sjxmbh,
      dgsyy: dataForm.dgsyy,
      lx: dataForm.lx,
      dbname: dbname
    };
    // send the request
    const res = await request('/cpasApi/draftManage/updateFileProperties', {
      method: 'POST',
      data: body,
    });
    if (res.ok) {
      const resFilter = resDataFilter(res.data);
      if (resFilter.success) {
        const { reDataArr } = resFilter;
        if (reDataArr.tempError.length) {
          const resNew = fjAndDgDataCode(reDataArr.tempError[0].code);
          return notify(`${resNew}!`, 'error', 3000);
        }
        notify("保存成功", "success", 2000);
        // onCloseDrawer();
        // 刷新数据
        RefreshFj(true);
      } else {
        notify('保存失败', 'error', 2000);
      }
    } else {
      notify('保存失败', 'error', 2000);
    }
  }
  return (
    <div style={{ height: 'calc(100% - 50px)', width: '100%' }}>
      <div style={{ width: '100%', height: '95%' }}>
        <Form formData={dataFormObj} width='100%' height='100%' className='FormStyle' >
          <GroupItem cssClass="second-group" colCount={1}>
            <GroupItem
              cssClass="first-group"
              colCount={4}
              style={{ marginBottom: '10px' }}
              caption={intl('paper.info', '底稿信息')}
            >
              <SimpleItem editorOptions={dataFormObj} render={(e: any) => {
                return <span style={{ fontSize: '50px', marginLeft: '12px' }}>{getCpasIcon(e.editorOptions.DGLX, 55)}</span>
              }} />
              <GroupItem colSpan={3}>
                <SimpleItem
                  dataField="DGMC"
                  name="dgmc"
                  label={{
                    // label控制标签内容
                    text: intl('paper.dgmc', '底稿名称'),
                    location: 'top',
                  }}
                />
              </GroupItem>
            </GroupItem>

            <GroupItem caption={intl('paper.syh', '索引号')}>
              <SimpleItem
                dataField="DGSYH"
                name="dgsyh"
                label={{
                  text: intl('paper.dgsyh', '底稿索引号'),
                  location: 'left',
                }}
              />
              <SimpleItem
                dataField="PaperIndexNo"
                name="PaperIndexNo"
                label={{
                  text: intl('paper.paperIndexNo', '纸质索引号'),
                  location: 'left',
                }}
                // editorOptions相关可查阅DevExtreme 使用组件相关文档 （textbox， selectbox， etc.)
                editorOptions={{
                  value: dataFormObj?.PaperIndexNo,
                }}
              />
            </GroupItem>

            <GroupItem caption={intl('paper.lx', '选项')}
            >
              {/* 此项目下的category和application是前端定义的，传入后端参数时在changeProperty里作了处理 */}
              <SimpleItem
                dataField="lx"
                editorType="dxSelectBox"
                editorOptions={{
                  items: dataFormLXItem,
                  value: dataFormObj?.lx,
                  placeholder: '无'
                }}
                label={{
                  text: intl('paper.lx', '底稿类别'),
                }}
              />
              <SimpleItem
                dataField="dgsyy"
                editorType="dxSelectBox"
                editorOptions={{
                  items: dataFormDgsyyItem,
                  value: dataFormObj?.dgsyy,
                  placeholder: '无'
                }}
                label={{
                  text: intl('paper.dgsyy', '适用于'),
                }}
              />
            </GroupItem>

            <GroupItem caption={intl('paper.edit', '编辑事项')}>
              <SimpleItem
                dataField="EditUser"
                label={{
                  text: intl('paper.editUser', '编辑人'),
                  location: 'left',
                }}
                editorOptions={{
                  disabled: true,
                }}
              />
              <SimpleItem
                dataField="EditDate"
                label={{
                  text: intl('paper.editDate', '编辑时间'),
                  location: 'left',
                }}
                editorOptions={{
                  disabled: true,
                  // value: data?.EditDate ? data?.EditDate : ''
                  value: dataFormObj?.EditDate === 'Invalid date' ? '' : dataFormObj?.EditDate,
                }}
              />
              <SimpleItem
                dataField="FilePath"
                label={{
                  text: '路径',
                  location: 'left',
                }}
                render={() => {
                  return <>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <TextBox
                        value={dataFormObj?.FilePath}
                        // readOnly={true}
                        disabled={true}
                      />
                      <Button
                        className="defaultReloadBtnWhite copyBtn"
                        icon='copy'
                        onClick={() => {
                          navigator.clipboard.writeText(dataFormObj?.FilePath);
                          notify({
                            message: '复制路径成功！',
                            type: 'success',
                          });
                        }} />
                    </div>

                  </>
                }}
              />
            </GroupItem>
          </GroupItem>
        </Form>
      </div>
      <div style={{ height: `${height <= 700 ? "20%" : "10%"}`, display: 'flex', alignItems: 'center', }}>
        <Button
          width={88}
          type="default"
          text={intl('paper.save', '保存')}
          onClick={async () => {
            changeProperty(dataFormObj, sjxmbh, dataFormObj?.DGID, dbname);
          }}
        />
        <Button
          width={88}
          text={intl('audit.cancel', '取消')}
          onClick={async () => {
            onCloseDrawer()
          }}
        />
      </div >
    </div >
  );
};



export default DgProps;
